<template>
  <el-dialog
    v-model="dialogFormVisible"
    :close-on-click-modal="false"
    :title="title"
    width="520"
    @close="close"
  >
    <el-form
      ref="formRef"
      label-width="120px"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="标题：" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="分类：" prop="category_id">
        <el-select
          v-model="form.category_id"
          placeholder="请选择分类"
          style="flex-grow: 1"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.category_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit } from '@/api/enterpriseWeChat/titleList'
  export default defineComponent({
    name: 'TableEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        formRef: null,
        treeRef: null,
        form: {
          id: '',
          title: '',
          category_id: '',
        },
        rules: {
          name: [{ required: true, trigger: 'blur', message: '请输入标题' }],
          category_id: [{ required: true, trigger: 'blur', message: '请选择分类' }],
        },
        title: '',
        categoryList: [],
        dialogFormVisible: false,
      })

      const showEdit = (categoryList,row) => {
        console.log(row)
        state.categoryList = categoryList
        if (!row) {
          state.title = '创建标题'
        } else {
          state.title = '编辑标题'
          state.form = Object.assign({}, row)
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { message } = await doEdit(state.form)
            $baseMessage(message, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }
      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
      }
    },
  })
</script>

<style lang="scss" scoped></style>
